#!/usr/bin/python3
# -*- coding:utf-8 -*-
import os
import sys
import numpy as np

LOSS = 1e-3  # 容忍偏差
MINIMUM = 1e-10  # 调整最小值


def verify_result(real_result_path, golden_path):
    try:
        real = np.fromfile(real_result_path, dtype=np.float16).astype(np.float32)
        golden = np.fromfile(golden_path, dtype=np.float16).astype(np.float32)

        if len(real) != len(golden):
            print(f"[ERROR] Length mismatch: {len(real)} vs {len(golden)}")
            return False

        abs_diff = np.abs(real - golden)
        rel_diff = abs_diff / (np.abs(golden) + MINIMUM)

        print("\n=== Verification Report ===")
        print(f"Total elements: {len(real)}")
        print(f"Max absolute error: {np.max(abs_diff):.6f}")
        print(f"Mean absolute error: {np.mean(abs_diff):.6f}")
        print(f"Max relative error: {np.max(rel_diff):.6f}")
        print(f"Mean relative error: {np.mean(rel_diff):.6f}")

        atol_fail = np.sum(abs_diff > LOSS)
        rtol_fail = np.sum(rel_diff > LOSS)

        print(f"\nTolerance Check (Threshold={LOSS}):")
        print(f"Absolute error failures: {atol_fail} ({atol_fail / len(real) * 100:.2f}%)")
        print(f"Relative error failures: {rtol_fail} ({rtol_fail / len(real) * 100:.2f}%)")

        if atol_fail > len(real) * LOSS or rtol_fail > len(real) * LOSS:
            worst_idx = np.argmax(abs_diff)
            print("\n=== Worst Case ===")
            print(f"Index: {worst_idx}")
            print(f"Real: {real[worst_idx]:.6f}")
            print(f"Golden: {golden[worst_idx]:.6f}")
            print(f"Abs diff: {abs_diff[worst_idx]:.6f}")
            print(f"Rel diff: {rel_diff[worst_idx]:.6f}")
            return False

        print("\n[SUCCESS] All checks passed!")
        return True

    except Exception as e:
        print(f"[ERROR] Verification failed: {str(e)}")
        return False


if __name__ == '__main__':
    real_path = sys.argv[1] if len(sys.argv) > 1 else "output/output_y.bin"
    golden_path = sys.argv[2] if len(sys.argv) > 2 else "output/golden.bin"

    if not os.path.exists(real_path):
        print(f"[ERROR] File not found: {real_path}")
        sys.exit(1)
    if not os.path.exists(golden_path):
        print(f"[ERROR] File not found: {golden_path}")
        sys.exit(1)

    sys.exit(0 if verify_result(real_path, golden_path) else 1)